﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RPGXEngine;

namespace RPGXEngine
{
    public class ScriptDataTree
    {
        #region Properties

        public List<Function> Functions
        {
            get { return _functions; }
            private set { _functions = value; }
        }
        private List<Function> _functions = new List<Function>();

        public Dictionary<string, Function> FunctionNameIndex
        {
            get { return _functionNameIndex; }
            private set { _functionNameIndex = value; }
        }
        private Dictionary<string, Function> _functionNameIndex = new Dictionary<string, Function>(StringComparer.InvariantCultureIgnoreCase);

        public Dictionary<int, Function> FunctionAddressIndex
        {
            get { return _functionAddressIndex; }
            set { _functionAddressIndex = value; }
        }
        private Dictionary<int, Function> _functionAddressIndex = new Dictionary<int, Function>();

        public Dictionary<string, int> FunctionNameAddressIndex
        {
            get { return _functionNameAddressIndex; }
            set { _functionNameAddressIndex = value; }
        }
        private Dictionary<string, int> _functionNameAddressIndex = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase);

        #endregion

        #region Internal Methods

        internal void AddressFunctions(List<Script> scripts)
        {
            if (scripts.Count == 0)
                return;

            // see if we are addressing ourself
            bool isSelf = false;
            foreach (var s in scripts)
            {
                if (s.DataTree == this)
                {
                    isSelf = true;
                    break;
                }
            }

            if(!isSelf)
                this.Functions.Clear();
            this.FunctionAddressIndex.Clear();
            this.FunctionNameIndex.Clear();
            this.FunctionNameAddressIndex.Clear();

            foreach (var s in scripts)
            {
                foreach (var f in s.DataTree.Functions)
                {
                    if(!isSelf)
                        this.Functions.Add(f);
                    this.FunctionNameIndex.Add(f.Name, f); // TODO: this will go bang if there is more than 1 function with the same name - need some compiler error checking in the future

                    int address = isSelf ? this.Functions.IndexOf(f) : this.Functions.Count - 1;

                    this.FunctionAddressIndex.Add(address, f);
                    this.FunctionNameAddressIndex.Add(f.Name, address);
                }
            }
        }

        #endregion
    }
}
